package com.alibaba.japan.club.runtime.springmvc.servlet.view.freemarker;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.view.AbstractTemplateView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import com.alibaba.japan.club.runtime.springmvc.servlet.view.freemarker.FreeMarkerFunction.LocaleFunction;
import com.alibaba.japan.club.runtime.springmvc.servlet.view.freemarker.FreeMarkerFunction.MessageFunction;
import com.alibaba.japan.club.runtime.springmvc.servlet.view.freemarker.FreeMarkerFunction.ThemeFunction;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 该类扩展自FreeMarkerView<br>
 * 添加了相关的freemarker内置函数
 * 
 * @author:shaochuan.wangsc
 * @date:2009-3-24
 * 
 */
public class JapanFreeMarkerView extends FreeMarkerView {

	private static final String FREEMARKER_ROOT_MODEL = "FreeMarkerRootModel";

	@SuppressWarnings("unchecked")
	@Override
	public void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
		RequestContext requestContext = (RequestContext) model
				.get(AbstractTemplateView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE);
		model.put("locale", new LocaleFunction());
		model.put("message", new MessageFunction(requestContext));
		model.put("theme", new ThemeFunction(requestContext));
		model.put(FREEMARKER_ROOT_MODEL, model);
	}

	/**
	 * Process the FreeMarker template to the servlet response.
	 * <p>
	 * Can be overridden to customize the behavior.
	 * 
	 * @param template the template to process
	 * @param model the model for the template
	 * @param response servlet response (use this to get the OutputStream or Writer)
	 * @throws IOException if the template file could not be retrieved
	 * @throws TemplateException if thrown by FreeMarker
	 * @see freemarker.template.Template#process(Object, java.io.Writer)
	 */
	@SuppressWarnings("unchecked")
	public void processTemplate(Template template, Map model, HttpServletResponse response) throws IOException,
			TemplateException {
		Writer writer = response.getWriter();
		StringWriter stringWriter = new StringWriter();
		template.process(model, stringWriter);
		writer.write(stringWriter.toString());
	}
}
